import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView, Text, Button, Image } from '@tarojs/components'
import { AtIcon } from 'taro-ui'
import { Header } from '../common/header';

import './cart.scss'
import '../common/header.scss'

let clickCart = true;

export class Cart extends Component {

  constructor(props){
    super(props);
    this.state = {
      goods:[],
      pay:0
    }
  }

  componentWillMount () { 
    
  }

  componentDidMount () { 
    console.log(222);

    let that = this;
    let user = Taro.getStorageSync('user');

    Taro.request({
      credentials:'include',
      url: 'https://guoxiaojian.guoxiaoge.cn/api/order/cart?token='+user.token,
      success:(res) => {
        if(res.statusCode === 200){
          if(res.data.status === 'SUCCESS'){
            let pay = 0;
            res.data.data.map(function(item){
              item.now_price = that.handleDel0(item.now_price);
              item.checked = true;
              pay = (item.now_price * 100) * item.buy_num / 100
            })
            that.setState({
              goods:res.data.data,
              pay:this.handleDel0(pay.toFixed(2))
            });
          }else{
            if(res.data.status === 'FAILED'){
              if(res.data.failedCode === 'NO_LOGIN'){
                Taro.navigateTo({
                  url:'/pages/login/login'
                });
              }
            }
          }
        }
      }
    })
  }

  componentWillUnmount () { }

  componentDidShow () { 
    console.log(2222);
  }

  componentDidHide () { }

  handleChange(gid){
    if(clickCart === false){
      return;
    }
    clickCart = false;

    let goods = this.state.goods;
    let pay = this.state.pay;
    for(let i=0; i< goods.length; i++){
      if(goods[i].id == gid){
        if(goods[i].checked === true){
          goods[i].checked = false;
          pay = (pay * 100 - goods[i].now_price * goods[i].buy_num * 100) / 100
        }else{
          goods[i].checked = true;
          pay = (pay * 100 + goods[i].now_price * goods[i].buy_num * 100) / 100
        }
      }
    }

    this.setState({
      goods:goods,
      pay:this.handleDel0(pay.toFixed(2))
    }, function(){
      clickCart = true;
    });
  }

  handleAddCart(gid, buyNum){
    if(clickCart === false){
      return;
    }
    clickCart = false;

    let num = buyNum + 1;
    let user = Taro.getStorageSync('user');
    Taro.request({
      credentials:'include',
      url: 'https://guoxiaojian.guoxiaoge.cn/api/order/cart/update',
      data:{
        g_id : gid,
        buy_num : num,
        token : user.token
      },
      method:'POST',
      success:(res) => {
        clickCart = true;
        if(res.statusCode === 200){
          if(res.data.status === 'SUCCESS'){
            let goods = this.state.goods;
            let pay = this.state.pay;
            for(let i=0; i< goods.length; i++){
              if(goods[i].id == gid){
                goods[i].buy_num = num;
                pay = (pay * 100 + goods[i].now_price * 100) / 100
              }
            }
            this.setState({
              goods:goods,
              pay:this.handleDel0(pay.toFixed(2))
            });
          }else{
            if(res.data.status === 'FAILED'){
              if(res.data.failedCode === 'NO_LOGIN'){
                Taro.navigateTo({
                  url:'/pages/login/login'
                });
              }
            }
          }
        }
      }
    })
  }
  handleReduceCart(gid, buyNum){
    if(clickCart === false){
      return;
    }
    clickCart = false;
    let num = buyNum - 1;
    let user = Taro.getStorageSync('user');
    Taro.request({
      credentials:'include',
      url: 'https://guoxiaojian.guoxiaoge.cn/api/order/cart/update',
      data:{
        g_id : gid,
        buy_num : num,
        token : user.token
      },
      method:'POST',
      success:(res) => {
        clickCart = true;
        if(res.statusCode === 200){
          if(res.data.status === 'SUCCESS'){
            let goods = this.state.goods;
            let pay = this.state.pay;
            for(let i=0; i< goods.length; i++){
              if(goods[i].id == gid){
                goods[i].buy_num = num;
                pay = (pay * 100 - goods[i].now_price * 100) / 100
              }
            }
            this.setState({
              goods:goods,
              pay:this.handleDel0(pay.toFixed(2))
            });
          }else{
            if(res.data.status === 'FAILED'){
              if(res.data.failedCode === 'NO_LOGIN'){
                Taro.navigateTo({
                  url:'/pages/login/login'
                });
              }
            }
          }
        }
      }
    })
  }

  handleDel0(number){
    const regexp=/(?:\.0*|(\.\d+?)0+)$/;
    let new_number = number.replace(regexp,'$1');
    return new_number;
  }

  handleJiSuan(){
    let goods = this.state.goods;
    let checkGoodsIds = '';
    for(let i=0; i< goods.length; i++){
      if(goods[i].checked === true){
        checkGoodsIds += goods[i].id +',';
      }
    }

    let user = Taro.getStorageSync('user');
    Taro.request({
      credentials:'include',
      url: 'https://guoxiaojian.guoxiaoge.cn/api/order/create',
      data:{
        g_id : checkGoodsIds,
        token : user.token
      },
      method:'POST',
      success:(res) => {
        clickCart = true;
        if(res.statusCode === 200){
          if(res.data.status === 'SUCCESS'){
            Taro.navigateTo({
              url: '/pages/order/confirm?id=' + res.data.data
            });
          }else{
            if(res.data.status === 'FAILED'){
              if(res.data.failedCode === 'NO_LOGIN'){
                Taro.navigateTo({
                  url:'/pages/login/login'
                });
              }
            }
          }
        }
      }
    })
  }

  render () {
    return (
      <View style={{marginBottom:this.props.mb}}>
       <Header 
          title='我的购物车'>
        </Header>
        {/* <View className='cart-title'>
          <View className='cart-title-content'>
              <Checkbox color="#F2CA26" checked={true} value='1'></Checkbox>
              <Text>果小贱-麓山名园店</Text>
              <View></View>
            </View>
          </View> */}
        <ScrollView>
          {
            this.state.goods.map(function(item){
              return <View className='cart-select'>
                      {
                        item.checked
                        ?
                        <AtIcon prefixClass='icon' value='xuanze' size='28' color='#F2CA26' onClick={this.handleChange.bind(this, item.id)}></AtIcon>
                        :
                        <AtIcon prefixClass='icon' value='weixuanzhongyuanquan' size='28' color='#8A857C' onClick={this.handleChange.bind(this, item.id)}></AtIcon>
                      }
                      {/* <Checkbox color="#F2CA26" checked={item.checked} value='1' onClick={this.handleChange.bind(this, item.id)}></Checkbox> */}
                      <View className="cart-goods">
                      <View className='goods-item-image'>
                        <Image src={item.small_image} mode='widthFix' />
                      </View>
                      <View className='goods-item-content'>
                        <Text className='goods-item-content-title'>{item.show_title}</Text>
                        <Text className='goods-item-content-info'>{item.slogan}</Text>
                        {/* <View className='goods-item-content-tags'>
                          <View className='goods-item-content-tages-item'>
                            满168赠可乐
                          </View>
                          <View className='goods-item-content-tages-item'>
                            满268赠百事
                          </View>
                        </View> */}
                        <View className='goods-item-content-buy'>
                          <View className='goods-item-content-buy-price'>
                            <View className='goods-item-content-buy-price-value'>￥{item.now_price}</View>
                            <View className='goods-item-content-buy-price-unio'>{item.unit}</View>
                          </View>
                          {
                              item.buy_num > 0
                              ?
                              <View className='goods-item-content-buy-addcart'>
                                <AtIcon value='subtract-circle' onClick={this.handleReduceCart.bind(this, item.id, item.buy_num)} size='22' color='#FF576A'></AtIcon>
                                <View className='goods-item-content-buy-num'>{item.buy_num}</View>
                                <AtIcon value='add-circle' onClick={this.handleAddCart.bind(this, item.id, item.buy_num)} size='22' color='#FF576A'></AtIcon>
                              </View>
                              :
                              <View className='goods-item-content-buy-addcart'>
                                <AtIcon value='add-circle' onClick={this.handleAddCart} size='22' color='#FF576A'></AtIcon>
                              </View>
                            }
                        </View>
                      </View>
                    </View>
                  </View>
            })
          }
        </ScrollView>
        <View className='cart-pay' style={{bottom:this.props.bm}}>
          <View className='cart-pay-total'>总金额: {this.state.pay}</View>
          <View className='cart-pay-button'>
            <Button onClick={this.handleJiSuan}>结算</Button>
          </View>
        </View>
      </View>
    )
  }
}